<template>
  <div class="crop-management">
    <div class="page-header">
      <h2>农作物管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增农作物
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="农作物名称">
          <el-input
            v-model="searchForm.cropName"
            placeholder="请输入农作物名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="农作物编码">
          <el-input
            v-model="searchForm.cropCode"
            placeholder="请输入农作物编码"
            clearable
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-cascader
            v-model="searchForm.categoryId"
            :options="categoryTree"
            :props="cascaderProps"
            placeholder="请选择分类"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
      >
        <el-table-column prop="cropCode" label="农作物编码" width="120" />
        <el-table-column prop="cropName" label="农作物名称" min-width="100" />
        <el-table-column prop="categoryName" label="所属分类" width="120" />
        <el-table-column prop="scientificName" label="学名" min-width="180" />
        <el-table-column prop="growthCycle" label="生长周期" width="100" />
        <el-table-column prop="seasonality" label="季节性" width="100" />
        <el-table-column prop="yieldPerUnit" label="单位产量" width="100">
          <template #default="{ row }">
            {{ row.yieldPerUnit }} {{ row.unit }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存数量" width="100">
          <template #default="{ row }">
            {{ row.stock }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="产品描述" min-width="220" show-overflow-tooltip />
       <el-table-column prop="imageUrl" label="产品图片" width="100">
          <template #default="{ row }">
            <el-image
              v-if="row.imageUrl"
              :src="row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              style="width: 40px; height: 40px; border-radius: 4px;"
              fit="cover"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              hide-on-click-modal
              preview-teleported
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="农作物编码" prop="cropCode">
              <el-input
                v-model="formData.cropCode"
                placeholder="请输入农作物编码"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="农作物名称" prop="cropName">
              <el-input
                v-model="formData.cropName"
                placeholder="请输入农作物名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-cascader
                v-model="formData.categoryId"
                :options="categoryTree"
                :props="cascaderProps"
                placeholder="请选择分类"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学名" prop="scientificName">
              <el-input
                v-model="formData.scientificName"
                placeholder="请输入学名"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="生长周期" prop="growthCycle">
              <el-input
                v-model="formData.growthCycle"
                placeholder="请输入生长周期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="季节性" prop="seasonality">
              <el-select v-model="formData.seasonality" placeholder="请选择季节性" style="width: 100%">
                <el-option label="春季" value="春季" />
                <el-option label="夏季" value="夏季" />
                <el-option label="秋季" value="秋季" />
                <el-option label="冬季" value="冬季" />
                <el-option label="全年" value="全年" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="单位产量" prop="yieldPerUnit">
              <el-input-number
                v-model="formData.yieldPerUnit"
                placeholder="请输入单位产量"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产量单位" prop="unit">
              <el-select v-model="formData.unit" placeholder="请选择单位" style="width: 100%">
                <el-option label="亩" value="亩" />
                <el-option label="公顷" value="公顷" />
                <el-option label="公斤" value="公斤" />
                <el-option label="吨" value="吨" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="库存数量" prop="stock">
              <el-input-number
                v-model="formData.stock"
                placeholder="请输入库存数量"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="产品描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入产品描述"
          />
        </el-form-item>

        <el-form-item label="产品图片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="handleUpload"
          >
            <img v-if="formData.imageUrl" :src="formData.imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const tableData = ref([])
const categoryTree = ref([])

// 搜索表单
const searchForm = reactive({
  cropName: '',
  cropCode: '',
  categoryId: []
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  id: '',
  cropCode: '',
  cropName: '',
  categoryId: [],
  scientificName: '',
  growthCycle: '',
  seasonality: '',
  yieldPerUnit: null,
  unit: '亩',
  stock: 0,
  description: '',
  imageUrl: ''
})

// 表单验证规则
const formRules = {
  cropCode: [
    { required: true, message: '请输入农作物编码', trigger: 'blur' }
  ],
  cropName: [
    { required: true, message: '请输入农作物名称', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 级联选择器配置
const cascaderProps = {
  value: 'id',
  label: 'categoryName',
  children: 'children',
  checkStrictly: true
}

// 计算属性
const isEdit = computed(() => !!formData.id)
const dialogTitle = computed(() => isEdit.value ? '编辑农作物' : '新增农作物')

// 方法
const handleSearch = () => {
  pagination.currentPage = 1
  loadTableData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    cropName: '',
    cropCode: '',
    categoryId: []
  })
  pagination.currentPage = 1
  loadTableData()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadTableData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadTableData()
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 根据分类ID获取完整路径
const getCategoryPath = (categoryId) => {
  const findPath = (categories, targetId, path = []) => {
    for (const category of categories) {
      if (category.id === targetId) {
        return [...path, category.id]
      }
      if (category.children) {
        const found = findPath(category.children, targetId, [...path, category.id])
        if (found) return found
      }
    }
    return null
  }
  
  return findPath(categoryTree.value, categoryId) || [categoryId]
}

const handleEdit = (row) => {
  resetForm()
  // 修复分类数据回显
  Object.assign(formData, {
    ...row,
    categoryId: getCategoryPath(row.categoryId) // 获取分类的完整路径
  })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除农作物 "${row.cropName}" 吗？`,
      '提示',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    
    // 调用删除API
    // await deleteCrop(row.id)
    ElMessage.success('删除成功')
    loadTableData()
  } catch (error) {
    // 用户取消删除
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 处理分类ID - 确保获取最后一级分类ID
    const submitData = {
      ...formData,
      categoryId: Array.isArray(formData.categoryId) 
        ? formData.categoryId[formData.categoryId.length - 1]  // 取数组最后一个元素
        : formData.categoryId
    }
    
    // 调用保存API
    if (isEdit.value) {
      // await updateCrop(submitData)
      ElMessage.success('更新成功')
    } else {
      // await addCrop(submitData)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleUpload = (options) => {
  // 模拟上传
  const file = options.file
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.imageUrl = e.target.result
    ElMessage.success('上传成功')
  }
  reader.readAsDataURL(file)
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: '',
    cropCode: '',
    cropName: '',
    categoryId: [],
    scientificName: '',
    growthCycle: '',
    seasonality: '',
    yieldPerUnit: null,
    unit: '亩',
    description: '',
    imageUrl: ''
  })
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await getCropList({
    //   ...searchForm,
    //   categoryId: searchForm.categoryId.length > 0 
    //     ? searchForm.categoryId[searchForm.categoryId.length - 1] 
    //     : null,
    //   page: pagination.currentPage,
    //   size: pagination.pageSize
    // })
    
    // 模拟数据
    const mockData = [
      // 粮食作物 - 谷物类
      {
        id: 1,
        cropCode: 'RIC001',
        cropName: '水稻',
        categoryId: 3,
        categoryName: '水稻',
        scientificName: 'Oryza sativa',
        growthCycle: '90-150天',
        seasonality: '夏季',
        yieldPerUnit: 500,
        unit: '亩',
        description: '主要粮食作物，中国南方主要种植',
        stock: 50000,
        imageUrl: 'https://images.unsplash.com/photo-1586773860418-d37222d8fce3?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },
      {
        id: 2,
        cropCode: 'WHE002',
        cropName: '小麦',
        categoryId: 4,
        categoryName: '小麦',
        scientificName: 'Triticum aestivum',
        growthCycle: '200-230天',
        seasonality: '冬季',
        yieldPerUnit: 400,
        unit: '亩',
        description: '北方主要粮食作物，制作面粉的原料',
        stock: 45000,
        imageUrl: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },
      {
        id: 3,
        cropCode: 'COR003',
        cropName: '玉米',
        categoryId: 5,
        categoryName: '玉米',
        scientificName: 'Zea mays',
        growthCycle: '100-120天',
        seasonality: '夏季',
        yieldPerUnit: 600,
        unit: '亩',
        description: '重要粮食和饲料作物',
        stock: 60000,
        imageUrl: 'https://images.unsplash.com/photo-1571575173700-afb9492e6a50?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },

      // 粮食作物 - 豆类
      {
        id: 4,
        cropCode: 'SOY004',
        cropName: '大豆',
        categoryId: 12,
        categoryName: '大豆',
        scientificName: 'Glycine max',
        growthCycle: '90-120天',
        seasonality: '夏季',
        yieldPerUnit: 150,
        unit: '亩',
        description: '重要的油料和蛋白质来源',
        stock: 20000,
        imageUrl: 'https://images.unsplash.com/photo-1598300042247-d088f8ab3a91?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },
      {
        id: 5,
        cropCode: 'MUN005',
        cropName: '绿豆',
        categoryId: 13,
        categoryName: '绿豆',
        scientificName: 'Vigna radiata',
        growthCycle: '60-90天',
        seasonality: '夏季',
        yieldPerUnit: 100,
        unit: '亩',
        description: '清热解毒，夏季消暑佳品',
        stock: 15000,
        imageUrl: 'https://images.unsplash.com/photo-1574323347407-f5e1ad6d020b?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },

      // 蔬菜 - 果菜类
      {
        id: 6,
        cropCode: 'TOM006',
        cropName: '番茄',
        categoryId: 53,
        categoryName: '番茄',
        scientificName: 'Solanum lycopersicum',
        growthCycle: '90-120天',
        seasonality: '夏季',
        yieldPerUnit: 5000,
        unit: '亩',
        description: '营养丰富的红色果实，富含维生素C',
        stock: 10000,
        imageUrl: 'https://images.unsplash.com/photo-1546470427-e212b7d31075?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },
      {
        id: 7,
        cropCode: 'CUC007',
        cropName: '黄瓜',
        categoryId: 54,
        categoryName: '黄瓜',
        scientificName: 'Cucumis sativus',
        growthCycle: '60-75天',
        seasonality: '夏季',
        yieldPerUnit: 3000,
        unit: '亩',
        description: '清脆可口的瓜类蔬菜',
        stock: 15000,
        imageUrl: 'https://images.unsplash.com/photo-1449300079327-02f967c1cdee?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },
      {
        id: 8,
        cropCode: 'PEP008',
        cropName: '辣椒',
        categoryId: 55,
        categoryName: '辣椒',
        scientificName: 'Capsicum annuum',
        growthCycle: '80-100天',
        seasonality: '夏季',
        yieldPerUnit: 2000,
        unit: '亩',
        description: '辛辣调味蔬菜，富含维生素',
        stock: 8000,
        imageUrl: 'https://images.unsplash.com/photo-1602922960041-0a69cbe79763?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },

      // 蔬菜 - 叶菜类
      {
        id: 9,
        cropCode: 'CAB009',
        cropName: '白菜',
        categoryId: 37,
        categoryName: '白菜',
        scientificName: 'Brassica rapa',
        growthCycle: '50-70天',
        seasonality: '秋季',
        yieldPerUnit: 4000,
        unit: '亩',
        description: '常见叶菜，营养丰富',
        stock: 20000,
        imageUrl: 'https://images.unsplash.com/photo-1540420773420-3366772f4999?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },
      {
        id: 10,
        cropCode: 'SPI010',
        cropName: '菠菜',
        categoryId: 38,
        categoryName: '菠菜',
        scientificName: 'Spinacia oleracea',
        growthCycle: '40-50天',
        seasonality: '春季',
        yieldPerUnit: 1500,
        unit: '亩',
        description: '富含铁质的绿叶蔬菜',
        stock: 12000,
        imageUrl: 'https://images.unsplash.com/photo-1576045057995-568f588f82fb?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },

      // 水果 - 仁果类
      {
        id: 11,
        cropCode: 'APP011',
        cropName: '苹果',
        categoryId: 67,
        categoryName: '苹果',
        scientificName: 'Malus domestica',
        growthCycle: '150-180天',
        seasonality: '秋季',
        yieldPerUnit: 3000,
        unit: '亩',
        description: '香甜可口，富含多种维生素',
        stock: 25000,
        imageUrl: 'https://images.unsplash.com/photo-1568702846914-96b305d2aaeb?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },
      {
        id: 12,
        cropCode: 'PEA012',
        cropName: '梨',
        categoryId: 68,
        categoryName: '梨',
        scientificName: 'Pyrus spp.',
        growthCycle: '140-170天',
        seasonality: '秋季',
        yieldPerUnit: 2500,
        unit: '亩',
        description: '多汁清甜，润肺止咳',
        stock: 18000,
        imageUrl: 'https://images.unsplash.com/photo-1615485290382-441e4d049cb5?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },

      // 水果 - 浆果类
      {
        id: 13,
        cropCode: 'GRA013',
        cropName: '葡萄',
        categoryId: 77,
        categoryName: '葡萄',
        scientificName: 'Vitis vinifera',
        growthCycle: '120-150天',
        seasonality: '夏季',
        yieldPerUnit: 1500,
        unit: '亩',
        description: '酿酒和鲜食佳品',
        stock: 12000,
        imageUrl: 'https://images.unsplash.com/photo-1517581177683-c3c0bb1d89d9?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },
      {
        id: 14,
        cropCode: 'STR014',
        cropName: '草莓',
        categoryId: 78,
        categoryName: '草莓',
        scientificName: 'Fragaria × ananassa',
        growthCycle: '60-90天',
        seasonality: '春季',
        yieldPerUnit: 2000,
        unit: '亩',
        description: '红色浆果，酸甜可口',
        stock: 8000,
        imageUrl: 'https://images.unsplash.com/photo-1464965911861-746a04b4bca6?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },

      // 畜禽产品 - 肉类
      {
        id: 15,
        cropCode: 'PIG015',
        cropName: '猪肉',
        categoryId: 100,
        categoryName: '猪肉',
        scientificName: 'Sus scrofa domesticus',
        growthCycle: '180-240天',
        seasonality: '全年',
        yieldPerUnit: 200,
        unit: '头',
        description: '主要肉类食品',
        stock: 5000,
        imageUrl: 'https://images.unsplash.com/photo-1589927986089-35812388d1f4?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },
      {
        id: 16,
        cropCode: 'CHI016',
        cropName: '鸡肉',
        categoryId: 103,
        categoryName: '鸡肉',
        scientificName: 'Gallus gallus domesticus',
        growthCycle: '45-60天',
        seasonality: '全年',
        yieldPerUnit: 2,
        unit: '只',
        description: '高蛋白低脂肪肉类',
        stock: 15000,
        imageUrl: 'https://images.unsplash.com/photo-1587593810167-a84920ea0781?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },

      // 畜禽产品 - 蛋类
      {
        id: 17,
        cropCode: 'EGG017',
        cropName: '鸡蛋',
        categoryId: 106,
        categoryName: '鸡蛋',
        scientificName: 'Gallus gallus domesticus',
        growthCycle: '21天',
        seasonality: '全年',
        yieldPerUnit: 300,
        unit: '只/年',
        description: '优质蛋白质来源',
        stock: 50000,
        imageUrl: 'https://images.unsplash.com/photo-1582722872445-44dc5f7e3c8f?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },

      // 水产品 - 鱼类
      {
        id: 18,
        cropCode: 'FIS018',
        cropName: '三文鱼',
        categoryId: 116,
        categoryName: '三文鱼',
        scientificName: 'Salmo salar',
        growthCycle: '24-36个月',
        seasonality: '全年',
        yieldPerUnit: 5000,
        unit: '吨',
        description: '富含Omega-3脂肪酸',
        stock: 3000,
        imageUrl: 'https://images.unsplash.com/photo-1519708227418-c8fd9a32b7a2?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },

      // 水产品 - 甲壳类
      {
        id: 19,
        cropCode: 'SHR019',
        cropName: '虾',
        categoryId: 121,
        categoryName: '虾',
        scientificName: 'Penaeus spp.',
        growthCycle: '4-6个月',
        seasonality: '全年',
        yieldPerUnit: 2000,
        unit: '吨',
        description: '高蛋白海鲜',
        stock: 2000,
        imageUrl: 'https://images.unsplash.com/photo-1558618047-3c8c76ca7d13?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      },

      // 油料作物
      {
        id: 20,
        cropCode: 'PEA020',
        cropName: '花生',
        categoryId: 26,
        categoryName: '花生',
        scientificName: 'Arachis hypogaea',
        growthCycle: '100-130天',
        seasonality: '夏季',
        yieldPerUnit: 300,
        unit: '亩',
        description: '重要的油料作物',
        stock: 15000,
        imageUrl: 'https://images.unsplash.com/photo-1558618047-3c8c76ca7d13?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
      }
    ]
    
    // 搜索过滤逻辑
    let filteredData = mockData.filter(item => {
      // 农作物名称过滤
      if (searchForm.cropName && !item.cropName.includes(searchForm.cropName)) {
        return false
      }
      
      // 农作物编号过滤（不区分大小写）
      if (searchForm.cropCode && 
          !item.cropCode.toLowerCase().includes(searchForm.cropCode.toLowerCase())) {
        return false
      }
      
      // 分类过滤 - 修改为支持多级分类搜索
      if (searchForm.categoryId && searchForm.categoryId.length > 0) {
        const selectedCategoryId = searchForm.categoryId[searchForm.categoryId.length - 1]
        
        // 查找该分类下的所有子分类ID（包括自身）
        const categoryIds = getCategoryAndChildrenIds(selectedCategoryId)
        
        // 检查当前项的分类ID是否在选中的分类及其子分类中
        if (!categoryIds.includes(item.categoryId)) {
          return false
        }
      }
      
      return true
    })

    // 分页处理
    const startIndex = (pagination.currentPage - 1) * pagination.pageSize
    const endIndex = startIndex + pagination.pageSize
    
    tableData.value = filteredData.slice(startIndex, endIndex)
    pagination.total = filteredData.length

    loadCategoryTree()
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 获取分类及其所有子分类的ID
const getCategoryAndChildrenIds = (categoryId) => {
  const ids = [categoryId]
  
  const findChildren = (categories) => {
    for (const category of categories) {
      if (category.id === categoryId) {
        // 找到目标分类，收集所有子分类ID
        if (category.children) {
          collectChildrenIds(category.children, ids)
        }
        return true
      }
      if (category.children) {
        if (findChildren(category.children)) {
          return true
        }
      }
    }
    return false
  }
  
  const collectChildrenIds = (categories, idArray) => {
    for (const category of categories) {
      idArray.push(category.id)
      if (category.children) {
        collectChildrenIds(category.children, idArray)
      }
    }
  }
  
  findChildren(categoryTree.value)
  return ids
}

// 加载分类树
const loadCategoryTree = async () => {
  try {
    // 模拟API调用获取分类树
    // const response = await getCategoryTree()
    
    const mockTree = [
      {
        id: 1,
        categoryCode: 'GRAIN',
        categoryName: '粮食作物',
        children: [
          {
            id: 2,
            categoryCode: 'CEREAL',
            categoryName: '谷物',
            children: [
              { id: 3, categoryCode: 'RICE', categoryName: '水稻' },
              { id: 4, categoryCode: 'WHEAT', categoryName: '小麦' },
              { id: 5, categoryCode: 'CORN', categoryName: '玉米' },
              { id: 6, categoryCode: 'BARLEY', categoryName: '大麦' },
              { id: 7, categoryCode: 'OATS', categoryName: '燕麦' },
              { id: 8, categoryCode: 'SORGHUM', categoryName: '高粱' },
              { id: 9, categoryCode: 'MILLET', categoryName: '小米' },
              { id: 10, categoryCode: 'BUCKWHEAT', categoryName: '荞麦' }
            ]
          },
          {
            id: 11,
            categoryCode: 'LEGUME',
            categoryName: '豆类',
            children: [
              { id: 12, categoryCode: 'SOYBEAN', categoryName: '大豆' },
              { id: 13, categoryCode: 'MUNGBEAN', categoryName: '绿豆' },
              { id: 14, categoryCode: 'REDBEAN', categoryName: '红豆' },
              { id: 15, categoryCode: 'BLACKBEAN', categoryName: '黑豆' },
              { id: 16, categoryCode: 'BROADBEAN', categoryName: '蚕豆' },
              { id: 17, categoryCode: 'PEA', categoryName: '豌豆' },
              { id: 18, categoryCode: 'KIDNEYBEAN', categoryName: '芸豆' }
            ]
          },
          {
            id: 19,
            categoryCode: 'TUBER',
            categoryName: '薯类',
            children: [
              { id: 20, categoryCode: 'POTATO', categoryName: '马铃薯' },
              { id: 21, categoryCode: 'SWEETPOTATO', categoryName: '甘薯' },
              { id: 22, categoryCode: 'CASSAVA', categoryName: '木薯' },
              { id: 23, categoryCode: 'YAM', categoryName: '山药' }
            ]
          }
        ]
      },
      {
        id: 24,
        categoryCode: 'OIL',
        categoryName: '油料作物',
        children: [
          { id: 25, categoryCode: 'RAPE_OIL', categoryName: '油菜' },
          { id: 26, categoryCode: 'PEANUT', categoryName: '花生' },
          { id: 27, categoryCode: 'SUNFLOWER', categoryName: '向日葵' },
          { id: 28, categoryCode: 'SESAME', categoryName: '芝麻' },
          { id: 29, categoryCode: 'OILTEA', categoryName: '油茶' }
        ]
      },
      {
        id: 30,
        categoryCode: 'VEGETABLE',
        categoryName: '蔬菜',
        children: [
          {
            id: 31,
            categoryCode: 'ROOT_VEGETABLE',
            categoryName: '根菜类',
            children: [
              { id: 32, categoryCode: 'RADISH', categoryName: '萝卜' },
              { id: 33, categoryCode: 'CARROT', categoryName: '胡萝卜' },
              { id: 34, categoryCode: 'SWEETPOTATO_VEG', categoryName: '甘薯' },
              { id: 35, categoryCode: 'POTATO_VEG', categoryName: '马铃薯' }
            ]
          },
          {
            id: 36,
            categoryCode: 'LEAF_VEGETABLE',
            categoryName: '叶菜类',
            children: [
              { id: 37, categoryCode: 'CABBAGE', categoryName: '白菜' },
              { id: 38, categoryCode: 'SPINACH', categoryName: '菠菜' },
              { id: 39, categoryCode: 'LETTUCE', categoryName: '生菜' },
              { id: 40, categoryCode: 'RAPE_VEG', categoryName: '油菜' },
              { id: 41, categoryCode: 'CHIVE', categoryName: '韭菜' }
            ]
          },
          {
            id: 42,
            categoryCode: 'STEM_VEGETABLE',
            categoryName: '茎菜类',
            children: [
              { id: 43, categoryCode: 'CELERY', categoryName: '芹菜' },
              { id: 44, categoryCode: 'ASPARAGUS', categoryName: '莴笋' },
              { id: 45, categoryCode: 'BAMBOO', categoryName: '竹笋' },
              { id: 46, categoryCode: 'LOTUS', categoryName: '藕' },
              { id: 47, categoryCode: 'ONION', categoryName: '洋葱' }
            ]
          },
          {
            id: 48,
            categoryCode: 'FLOWER_VEGETABLE',
            categoryName: '花菜类',
            children: [
              { id: 49, categoryCode: 'CAULIFLOWER', categoryName: '花椰菜' },
              { id: 50, categoryCode: 'BROCCOLI', categoryName: '西兰花' },
              { id: 51, categoryCode: 'LILY_VEG', categoryName: '黄花菜' }
            ]
          },
          {
            id: 52,
            categoryCode: 'FRUIT_VEGETABLE',
            categoryName: '果菜类',
            children: [
              { id: 53, categoryCode: 'TOMATO', categoryName: '番茄' },
              { id: 54, categoryCode: 'CUCUMBER', categoryName: '黄瓜' },
              { id: 55, categoryCode: 'PEPPER', categoryName: '辣椒' },
              { id: 56, categoryCode: 'EGGPLANT', categoryName: '茄子' },
              { id: 57, categoryCode: 'PUMPKIN', categoryName: '南瓜' },
              { id: 58, categoryCode: 'WAXGOURD', categoryName: '冬瓜' }
            ]
          },
          {
            id: 59,
            categoryCode: 'MUSHROOM',
            categoryName: '食用菌类',
            children: [
              { id: 60, categoryCode: 'SHIITAKE', categoryName: '香菇' },
              { id: 61, categoryCode: 'OYSTER_MUSHROOM', categoryName: '平菇' },
              { id: 62, categoryCode: 'ENOKI', categoryName: '金针菇' },
              { id: 63, categoryCode: 'WOODEAR', categoryName: '木耳' },
              { id: 64, categoryCode: 'TREMELLA', categoryName: '银耳' }
            ]
          }
        ]
      },
      {
        id: 65,
        categoryCode: 'FRUIT',
        categoryName: '水果',
        children: [
          {
            id: 66,
            categoryCode: 'POME_FRUIT',
            categoryName: '仁果类',
            children: [
              { id: 67, categoryCode: 'APPLE', categoryName: '苹果' },
              { id: 68, categoryCode: 'PEAR', categoryName: '梨' },
              { id: 69, categoryCode: 'HAWTHORN', categoryName: '山楂' }
            ]
          },
          {
            id: 70,
            categoryCode: 'STONE_FRUIT',
            categoryName: '核果类',
            children: [
              { id: 71, categoryCode: 'PEACH', categoryName: '桃' },
              { id: 72, categoryCode: 'PLUM', categoryName: '李' },
              { id: 73, categoryCode: 'APRICOT', categoryName: '杏' },
              { id: 74, categoryCode: 'MUME', categoryName: '梅' },
              { id: 75, categoryCode: 'CHERRY', categoryName: '樱桃' }
            ]
          },
          {
            id: 76,
            categoryCode: 'BERRY_FRUIT',
            categoryName: '浆果类',
            children: [
              { id: 77, categoryCode: 'GRAPE', categoryName: '葡萄' },
              { id: 78, categoryCode: 'STRAWBERRY', categoryName: '草莓' },
              { id: 79, categoryCode: 'BLUEBERRY', categoryName: '蓝莓' },
              { id: 80, categoryCode: 'KIWI', categoryName: '猕猴桃' },
              { id: 81, categoryCode: 'POMEGRANATE', categoryName: '石榴' }
            ]
          },
          {
            id: 82,
            categoryCode: 'CITRUS_FRUIT',
            categoryName: '柑橘类',
            children: [
              { id: 83, categoryCode: 'CITRUS', categoryName: '柑橘' },
              { id: 84, categoryCode: 'ORANGE', categoryName: '橙' },
              { id: 85, categoryCode: 'POMELO', categoryName: '柚' },
              { id: 86, categoryCode: 'LEMON', categoryName: '柠檬' }
            ]
          },
          {
            id: 87,
            categoryCode: 'MELON_FRUIT',
            categoryName: '瓜果类',
            children: [
              { id: 88, categoryCode: 'WATERMELON', categoryName: '西瓜' },
              { id: 89, categoryCode: 'MELON', categoryName: '甜瓜' },
              { id: 90, categoryCode: 'HAMI', categoryName: '哈密瓜' }
            ]
          },
          {
            id: 91,
            categoryCode: 'TROPICAL_FRUIT',
            categoryName: '热带水果',
            children: [
              { id: 92, categoryCode: 'BANANA', categoryName: '香蕉' },
              { id: 93, categoryCode: 'PINEAPPLE', categoryName: '菠萝' },
              { id: 94, categoryCode: 'MANGO', categoryName: '芒果' },
              { id: 95, categoryCode: 'LITCHI', categoryName: '荔枝' },
              { id: 96, categoryCode: 'LONGAN', categoryName: '龙眼' },
              { id: 97, categoryCode: 'COCONUT', categoryName: '椰子' }
            ]
          }
        ]
      },
      {
        id: 98,
        categoryCode: 'LIVESTOCK',
        categoryName: '畜禽产品',
        children: [
          {
            id: 99,
            categoryCode: 'MEAT',
            categoryName: '肉类',
            children: [
              { id: 100, categoryCode: 'PORK', categoryName: '猪肉' },
              { id: 101, categoryCode: 'BEEF', categoryName: '牛肉' },
              { id: 102, categoryCode: 'MUTTON', categoryName: '羊肉' },
              { id: 103, categoryCode: 'CHICKEN_MEAT', categoryName: '鸡肉' },
              { id: 104, categoryCode: 'DUCK_MEAT', categoryName: '鸭肉' }
            ]
          },
          {
            id: 105,
            categoryCode: 'EGG',
            categoryName: '蛋类',
            children: [
              { id: 106, categoryCode: 'CHICKEN_EGG', categoryName: '鸡蛋' },
              { id: 107, categoryCode: 'DUCK_EGG', categoryName: '鸭蛋' },
              { id: 108, categoryCode: 'GOOSE_EGG', categoryName: '鹅蛋' },
              { id: 109, categoryCode: 'QUAIL_EGG', categoryName: '鹌鹑蛋' }
            ]
          },
          {
            id: 110,
            categoryCode: 'MILK',
            categoryName: '奶类',
            children: [
              { id: 111, categoryCode: 'COW_MILK', categoryName: '牛奶' },
              { id: 112, categoryCode: 'GOAT_MILK', categoryName: '羊奶' }
            ]
          }
        ]
      },
      {
        id: 113,
        categoryCode: 'AQUATIC',
        categoryName: '水产品',
        children: [
          {
            id: 114,
            categoryCode: 'FISH',
            categoryName: '鱼类',
            children: [
              { id: 115, categoryCode: 'TUNA', categoryName: '金枪鱼' },
              { id: 116, categoryCode: 'SALMON', categoryName: '三文鱼' },
              { id: 117, categoryCode: 'COD', categoryName: '鳕鱼' },
              { id: 118, categoryCode: 'HAIRTAIL', categoryName: '带鱼' },
              { id: 119, categoryCode: 'CROAKER', categoryName: '黄花鱼' }
            ]
          },
          {
            id: 120,
            categoryCode: 'CRUSTACEAN',
            categoryName: '甲壳类',
            children: [
              { id: 121, categoryCode: 'SHRIMP', categoryName: '虾' },
              { id: 122, categoryCode: 'CRAB', categoryName: '蟹' }
            ]
          },
          {
            id: 123,
            categoryCode: 'SHELLFISH',
            categoryName: '贝类',
            children: [
              { id: 124, categoryCode: 'OYSTER_AQUATIC', categoryName: '牡蛎' },
              { id: 125, categoryCode: 'CLAM', categoryName: '蛤蜊' },
              { id: 126, categoryCode: 'SCALLOP', categoryName: '扇贝' },
              { id: 127, categoryCode: 'MUSSEL', categoryName: '贻贝' },
              { id: 128, categoryCode: 'ABALONE', categoryName: '鲍鱼' }
            ]
          }
        ]
      }
    ]
    
    categoryTree.value = mockTree
  } catch (error) {
    console.error('加载分类树失败:', error)
  }
}

onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.crop-management {
  padding: 20px;
  background: white;
  border-radius: 8px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
  }
  
  :deep(.el-upload:hover) {
    border-color: #409eff;
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
  border-radius: 4px;
}

/* 图片预览样式优化 */
:deep(.el-image-viewer__wrapper) {
  z-index: 9999;
}

:deep(.el-image-viewer__img) {
  max-width: 80vw;
  max-height: 80vh;
}
</style>